/**
 * 
 */

package com.chengyu.eyc.interceptor;

import java.util.Map;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import com.chengyu.eyc.constant.EycConstants;

import lombok.extern.slf4j.Slf4j;

/**
 * @author kevin
 *
 */
@Slf4j
public class EycHandshakeInterceptor extends HttpSessionHandshakeInterceptor {

    /**
     * @see org.springframework.web.socket.server.HandshakeInterceptor#afterHandshake(org.springframework.http.server.ServerHttpRequest,
     *      org.springframework.http.server.ServerHttpResponse, org.springframework.web.socket.WebSocketHandler,
     *      java.lang.Exception)
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        log.info("afterHandshake");
        super.afterHandshake(request, response, wsHandler, exception);
    }

    /**
     * @see org.springframework.web.socket.server.HandshakeInterceptor#beforeHandshake(org.springframework.http.server.ServerHttpRequest,
     *      org.springframework.http.server.ServerHttpResponse, org.springframework.web.socket.WebSocketHandler,
     *      java.util.Map)
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        log.info("beforeHandshake");
        if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null) {
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (principal instanceof UserDetails) {
                attributes.put(EycConstants.USER_ID, principal);
            }
        }else {
            return false;
        }
     
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

}
